package cqupt.spark_log.info;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cqupt.spark_log.entity.Job;
import cqupt.spark_log.runable.Monitor;
import cqupt.spark_log.utils.ECUtil;

public class EnergyInfo {
	private BanchInfo banchInfo;

	public EnergyInfo(BanchInfo banchInfo) {
		this.banchInfo = banchInfo;
	}
	private final CountDownLatch countDownLatch = new CountDownLatch(6);
	public void run() {
		Monitor monitor171 = new Monitor(banchInfo, "monitor-171",countDownLatch);
		Monitor monitor172 = new Monitor(banchInfo, "monitor-172",countDownLatch);
		Monitor monitor173 = new Monitor(banchInfo, "monitor-173",countDownLatch);
		Monitor monitor175 = new Monitor(banchInfo, "monitor-175",countDownLatch);
		Monitor monitor176 = new Monitor(banchInfo, "monitor-176",countDownLatch);
		Monitor monitor177 = new Monitor(banchInfo, "monitor-177",countDownLatch);
		ExecutorService executors = Executors.newFixedThreadPool(6);
		executors.submit(monitor171);
		executors.submit(monitor172);
		executors.submit(monitor173);
		executors.submit(monitor175);
		executors.submit(monitor176);
		executors.submit(monitor177);
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executors.shutdown();
	}
	
	public double calculate () {
		Map<String, Job> jobs = banchInfo.getJobs();
		double appEC = 0;
		for (String key: jobs.keySet()) {
			Job job = jobs.get(key);
			appEC += job.getEc();
		}
		return ECUtil.get4point(appEC);
	}
	//只计算某一个阶段的能耗
	public double calculate(String stageName) {
		String[] jobAndStage = stageName.split(";");
		Map<String, Job> jobs = banchInfo.getJobs();
		double appEC = 0;
		for (String key: jobs.keySet()) {
			if (key.equals(jobAndStage[0])) {
				Job job = jobs.get(key);
				appEC += job.getEc(stageName);
				break;
			}
		}
		return ECUtil.get4point(appEC);
	}

	public long getStageTime(String stageName) {
		String[] jobAndStage = stageName.split(";");
		Map<String, Job> jobs = banchInfo.getJobs();
		for (String key: jobs.keySet()) {
			if (key.equals(jobAndStage[0])) {
				Job job = jobs.get(key);
				return job.getStageTime(stageName);
			}
		}
		return 0;
	}
}
